package com.itfenghuang.controller;

import com.itfenghuang.bean.User;
import com.itfenghuang.service.UserService;
import com.itfenghuang.service.imp.UserServiceImp;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@SuppressWarnings("all")
public class RegisterServlet extends HttpServlet {
    private UserService service=new UserServiceImp();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //1.获取请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String password1 = req.getParameter("password1");
        //2.判断密码是否一样 字符串比较相等equals
        if (!password.equals(password1)){
            //Refresh: 定时刷新  2秒后,URL:跳转到指定的页面  虚拟目录+访问资源路径
            resp.setHeader("Refresh","2;URL=/stusys/register.jsp");
            //告诉用户两次输入密码不一致
            resp.getWriter().write("密码不一致,2秒后跳转到注册页面");
            return;
        }
        //密码相等的时候
        String s = service.addUser(new User(0, username, password));
        if ("用户名已存在".equals(s)){
            //将数据存到请求域
            req.setAttribute("error",s);
            //将请求转达到注册页面,在注册页面上给用户一个提示
            req.getRequestDispatcher("/register.jsp").forward(req,resp);
        }else {
            String str="<a href='/stusys/login.jsp'>注册成功,点击登陆</a>";
            resp.getWriter().write(str);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
    }
}
